package com.zuma.oci.docker.handler;

import com.zuma.oci.docker.transport.DockerEngineV2Exception;
import org.apache.hc.core5.http.ClassicHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.Consumer;

public class ImagePushHandler extends IResponseProcessHandler<String> {
    private Consumer<PushImageLinePrint> tailFunc;

    private String imageId;

    public ImagePushHandler(Consumer<PushImageLinePrint> tailFunc) {
        this.tailFunc = tailFunc;
    }

    @Override
    public String process(ClassicHttpResponse response) {
        if (response.getEntity() != null) {
            try (var is = response.getEntity().getContent(); var reader = new BufferedReader(new InputStreamReader(is))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    var lineResult = PushImageLinePrint.build(line);
                    if (tailFunc != null) {
                        tailFunc.accept(lineResult);
                    }
                }
            } catch (IOException e) {
                throw new DockerEngineV2Exception(this.getHost(), this.getUrl(), response.getCode(), response.getReasonPhrase(), e.getMessage());
            }
        }
        return "succcess";
    }
}
